<?php
class Mageex_AdvanceSeo_Model_Sitemap extends Mage_Sitemap_Model_Sitemap
{
    /*
	*	Check number split
	*/
	public function check_counter($io,$ioindex,$url) {
        static $counter;
        $counter++;
		$limit 		= (int)Mage::helper('advanceseo/sitemap')->getMaximumUrl();
		$limitSize 	= (int)Mage::helper('advanceseo/sitemap')->getFileSize();
		$fileSize	= filesize($this->getSitemapFilename()); 
        if (((int)($counter/$limit) == $counter/$limit) || ($limitSize == $fileSize)) {
            $io->streamWrite('</urlset>');
            $io->streamClose();
            $filename = preg_replace('/\.xml/', '-'.round($counter/$limit).'.xml', $this->getSitemapFilename());
            $io->streamOpen($filename);
            $io->streamWrite('<?xml version="1.0" encoding="UTF-8"?>' . "\n");
            $io->streamWrite('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">');
			$ioindex->streamWrite(sprintf('<sitemap><loc>%s</loc><lastmod>%s</lastmod></sitemap>',
                htmlspecialchars($url . $filename),
                Mage::getSingleton('core/date')->gmtDate('Y-m-d')
            ));
        }
    }
	/*
	*	Generate site map
	*/
	public function generateXml()
    {
		if(Mage::helper('advanceseo/sitemap')->isEnabled()){
			$io = new Varien_Io_File();
			$io->setAllowCreateFolders(true);
			$io->open(array('path' => $this->getPath()));
			//Site map index 
			$ioindex = new Varien_Io_File();
			$ioindex ->setAllowCreateFolders(true);
			$ioindex ->open(array('path' => $this->getPath()));
			$url 	 = Mage::getBaseUrl().trim($this->getSitemapPath(), '/').'/';
			
			if ($io->fileExists($this->getSitemapFilename()) && !$io->isWriteable($this->getSitemapFilename())) {
				Mage::throwException(Mage::helper('sitemap')->__('File "%s" cannot be saved. Please, make sure the directory "%s" is writeable by web server.', $this->getSitemapFilename(), $this->getPath()));
			}
			if($ioindex->fileExists($this->getSitemapFilename()) 
				&& !$ioindex->isWriteable($this->getSitemapFilename())){
				Mage::throwException(Mage::helper('sitemap')->__('File "%s" cannot be saved. Please, make sure the directory "%s" is writeable by web server.', 'sitemapindex-'.$this->getSitemapFilename(), $this->getPath()));
			}
			$io->streamOpen($this->getSitemapFilename());
			$ioindex->streamOpen('sitemapindex-'.$this->getSitemapFilename());
			
			$io->streamWrite('<?xml version="1.0" encoding="UTF-8"?>' . "\n");
			$io->streamWrite('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">');
			
			$ioindex->streamWrite('<?xml version="1.0" encoding="UTF-8"?>' . "\n");
			$ioindex->streamWrite('<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">');
			
			$storeId = $this->getStoreId();
			$date    = Mage::getSingleton('core/date')->gmtDate('Y-m-d');
			$baseUrl = Mage::app()->getStore($storeId)->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);
			$ioindex->streamWrite(sprintf('<sitemap><loc>%s</loc><lastmod>%s</lastmod></sitemap>',
					htmlspecialchars($url . $this->getSitemapFilename()),
					$date
				));
			/**
			 * Generate categories sitemap
			 */ 
			$changefreq = (string)Mage::getStoreConfig('sitemap/category/changefreq', $storeId);
			$priority   = (string)Mage::getStoreConfig('sitemap/category/priority', $storeId);
			$collection = Mage::getResourceModel('sitemap/catalog_category')->getCollection($storeId);
			
			foreach ($collection as $item) {
				$xml[] = sprintf('<url><loc>%s</loc><lastmod>%s</lastmod><changefreq>%s</changefreq><priority>%.1f</priority></url>',
					htmlspecialchars($baseUrl . $item->getUrl()),
					$date,
					$changefreq,
					$priority
				);
			}
			unset($collection);

			/**
			 * Generate products sitemap
			 */
			$changefreq = (string)Mage::getStoreConfig('sitemap/product/changefreq', $storeId);
			$priority   = (string)Mage::getStoreConfig('sitemap/product/priority', $storeId);
			$collection = Mage::getResourceModel('sitemap/catalog_product')->getCollection($storeId);
			foreach ($collection as $item) {
				$xml[] = sprintf('<url><loc>%s</loc><lastmod>%s</lastmod><changefreq>%s</changefreq><priority>%.1f</priority></url>',
					htmlspecialchars($baseUrl . $item->getUrl()),
					$date,
					$changefreq,
					$priority
				);
			}
			unset($collection);
			
			/**
			 * Generate products search sitemap
			 */
			if(Mage::helper('advanceseo/config')->isEnableRewriteSearch()){
				$changefreq = (string)Mage::getStoreConfig('sitemap/review/changefreq', $storeId);
				$priority   = (string)Mage::getStoreConfig('sitemap/review/priority', $storeId);
				$collection = Mage::getModel('catalogsearch/query')->getCollection();
				//Path result search
				$suffix = Mage::helper('advanceseo/config')->getPathSearch();
				foreach ($collection as $item) {
					$param = Mage::helper('advanceseo/data')->stringConvert($item->getQueryText());
					//Url rewrite
					$path = $suffix . '/' . $param . Mage::helper('advanceseo/data')->getSuffix();
					//Check number result
					if($item->getNumResults()>0){
						$xml[] = sprintf('<url><loc>%s</loc><lastmod>%s</lastmod><changefreq>%s</changefreq><priority>%.1f</priority></url>',
							htmlspecialchars($baseUrl . $path),
							$date,
							$changefreq,
							$priority
						);
					}
				}
				unset($collection);
			}
			
			/**
			 * Generate products review sitemap
			 */
			if(Mage::helper('advanceseo/config')->isRewriteReview()){
				$changefreq = (string)Mage::getStoreConfig('sitemap/review/changefreq', $storeId);
				$priority   = (string)Mage::getStoreConfig('sitemap/review/priority', $storeId);
				//Get collection url review
				$collection = Mage::getModel('core/url_rewrite')->getCollection()->addFieldToFilter('is_system', 0);
				foreach ($collection as $item) {
					if(preg_match("/review/i",$item->getTargetPath())){
						$xml[] = sprintf('<url><loc>%s</loc><lastmod>%s</lastmod><changefreq>%s</changefreq><priority>%.1f</priority></url>',
						htmlspecialchars($baseUrl . $item->getRequestPath()),
						$date,
						$changefreq,
						$priority
						);
					}
				}
				unset($collection);
			}
			
			/**
			 * Generate tags sitemap
			 */
			if(Mage::helper('advanceseo/config')->isEnableRewriteTags()){
		
				$changefreq = (string)Mage::getStoreConfig('sitemap/tags/changefreq', $storeId);
				$priority   = (string)Mage::getStoreConfig('sitemap/tags/priority', $storeId);
				$collection = Mage::getModel('core/url_rewrite')->getCollection()->addFieldToFilter('is_system', 0);
				foreach ($collection as $item) {
					// get path tag
					if(preg_match("/tag/i",$item->getTargetPath())){
						$xml[] = sprintf('<url><loc>%s</loc><lastmod>%s</lastmod><changefreq>%s</changefreq><priority>%.1f</priority></url>',
						htmlspecialchars($baseUrl . $item->getRequestPath()),
						$date,
						$changefreq,
						$priority
						);
					}
				}
				unset($collection);
			}
			 
			/**
			 * Generate cms pages sitemap
			 */
			$changefreq = (string)Mage::getStoreConfig('sitemap/page/changefreq', $storeId);
			$priority   = (string)Mage::getStoreConfig('sitemap/page/priority', $storeId);
			$collection = Mage::getResourceModel('sitemap/cms_page')->getCollection($storeId);
			foreach ($collection as $item) {
				$xml[] = sprintf('<url><loc>%s</loc><lastmod>%s</lastmod><changefreq>%s</changefreq><priority>%.1f</priority></url>',
					htmlspecialchars($baseUrl . $item->getUrl()),
					$date,
					$changefreq,
					$priority
				);
			}
			unset($collection);
			
			foreach($xml as $stream)
			{
				$io->streamWrite($stream);
				$this->check_counter($io,$ioindex,$url);
			}
			$io->streamWrite('</urlset>');
			$io->streamClose();
			$ioindex->streamWrite('</sitemapindex>');
			$ioindex->streamClose();
			$this->setSitemapTime(Mage::getSingleton('core/date')->gmtDate('Y-m-d H:i:s'));
			/*$data['sitemapindex'] = 'sitemapindex';
			$this->setData($data);*/
			$this->save();

			return $this;
		}
    }
	
}
